package com.lzy.cloud.ticket.train.facade;

import com.lzy.cloud.ticket.train.constant.LMMApi;
import com.lzy.cloud.ticket.train.constant.LMMContant;
import com.lzy.cloud.ticket.train.dtos.SearchInfoDto;
import com.lzy.cloud.ticket.train.request.BaseRequest;
import com.lzy.cloud.ticket.train.request.SearchRequest;
import com.lzy.cloud.ticket.train.request.app.SearchAppRequest;
import com.lzy.cloud.ticket.train.response.SearchResponse;
import com.lzy.cloud.ticket.train.util.BasePushUtil;
import com.lzy.framework.core.ensure.Ensure;
import com.lzy.framework.core.output.Result;
import com.lzy.framework.core.utils.DozerUtils;
import com.lzy.framework.core.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
@Slf4j
public class SearchFacade {

    @Resource
    private RestTemplate restTemplate;

    @Autowired
    private BasePushUtil basePushUtil;

    /**
     * 筛选请求
     * @param searchAppRequest
     * @return
     */
    public Result queryTicketsFilter(SearchAppRequest searchAppRequest){
        SearchResponse searchResponse = search(searchAppRequest);
        if(null != searchResponse && null != searchResponse.getData()){
            List<SearchInfoDto> searchInfoDtos = searchResponse.getData().getTrainSeachVoList();
            if(null != searchInfoDtos && searchInfoDtos.size() > 0){
                Iterator<SearchInfoDto> iterator = searchInfoDtos.iterator();

                /*高级筛选*/
                //获取火车车次类型
                List trainTypeList = null;
                if (StringUtil.isNotBlank(searchAppRequest.getTrainTypes())) {
                    trainTypeList = Arrays.asList(searchAppRequest.getTrainTypes().replaceAll(" ", "").split(","));
                }
                //获取出发时间
                List trainTime = null;
                if (StringUtil.isNotBlank(searchAppRequest.getTrainTime())) {
                    trainTime = Arrays.asList(searchAppRequest.getTrainTime().replaceAll(" ", "").split(","));
                }
                SimpleDateFormat dfTime = new SimpleDateFormat("yyyy-MM-dd HH:mm");

                while (iterator.hasNext()) {
                    SearchInfoDto response = iterator.next();
                    //车次类型筛选
                    if (trainTypeList != null && trainTypeList.size() > 0) {
                        if (!trainTypeList.contains(
                                response.getTrainCode().substring(0,1))) {
                            iterator.remove();
                            searchInfoDtos.remove(response);
                            continue;
                        }
                    }
                    //发车时间筛选
                    if (trainTime != null && trainTime.size() > 0) {
                        boolean flag = false;
                        try {
                            for(Object time : trainTime){
                                String[] times = time.toString().split("-");
                                String format = "HH:mm";
                                Date startTime = new SimpleDateFormat(format).parse(times[0]);
                                Date endTime = new SimpleDateFormat(format).parse(times[1]);
                                Date nowTime = new SimpleDateFormat(format).parse(response.getFromTime());
                                if(isEffectiveDate(nowTime, startTime, endTime)){
                                    flag = true;
                                    break;
                                }
                            }
                        } catch (ParseException e) {
                            e.printStackTrace();
                            Ensure.that(e.getMessage()).isNull("00010012");
                        }
                        if (!flag) {
                            iterator.remove();
                            searchInfoDtos.remove(response);
                            continue;
                        }
                    }
                }
            }
        }
        return new Result(searchResponse.getData());
    }

    /**
     * 余票请求
     * @param searchAppRequest
     * @return
     */
    public SearchResponse search(SearchAppRequest searchAppRequest){
        BaseRequest baseRequest = basePushUtil.push(LMMContant.APP_KEY,LMMContant.SEARCH_METHOD,LMMContant.MESSAGE_FORMT,"");
        SearchRequest searchRequest = DozerUtils.map(baseRequest,SearchRequest.class);
        searchRequest.setData(searchAppRequest);
        SearchResponse searchResponse = restTemplate.postForObject(LMMApi.SEARCH_URL,searchRequest,SearchResponse.class);
        return searchResponse;
    }

    /**
     * 判断当前时间是否在[startTime, endTime]区间，注意时间格式要一致
     *
     * @param nowTime 当前时间
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return
     */
    public boolean isEffectiveDate(Date nowTime, Date startTime, Date endTime) {
        if (nowTime.getTime() == startTime.getTime()
                || nowTime.getTime() == endTime.getTime()) {
            return true;
        }

        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(startTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }
    }

}
